﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Zxb.DayWork.Core;

namespace Zxb.DayWork.Logic
{
    public class BBSWorker : BatchLoopWorker
    {
        //DataTable bbsDomainTable;
        Dictionary<string, string> cityDomain = new Dictionary<string, string>();
        DataTable targetTable;
        bool hasNew = true;
        string urlFormat;
        int currentMaxID = 0;
        int _pageLength;

        public BBSWorker(int pageLength)
        {
            _pageLength = pageLength;
            urlFormat = System.Configuration.ConfigurationManager.AppSettings["bbs_statProj4Home"];
        }

        private void InitCityDic()
        {
            DataTable dt = ReadDtDomain();
            foreach (DataRow dr in dt.Rows)
            {
                string city = dr["cityname"].ToString().Trim();
                string domain = dr["domain"].ToString().Trim();
                cityDomain[city] = domain;
            }
        }
        private static DataTable ReadDtDomain()
        {
            string sql = "select cityname,domain from bbsCityDomain with(nolock)";
            return DAL.ReadDt_Retry_ReturnNewIfNull(DB.ZxbReader, sql);
        }
        private DataTable ReadDtEstateManage()
        {
            string sql = string.Format("select top {0} id,RealEstateID,bbsTotalHits,bbsTotalClicks,bbsTotalTopics,bbsCertifiedOwners,City from EstateManage with(nolock) where id>{1} order by id", _pageLength, currentMaxID);
            return DAL.ReadDt_Retry_ReturnNewIfNull(DB.ZxbReader, sql);
        }

        protected override void ReadData()
        {
            if (!hasNew)
            {
                return;
            }
            targetTable = ReadDtEstateManage();
            if (targetTable.Rows.Count == 0)
            {
                hasNew = false;
            }
        }

        protected override void ProcessData()
        {
            if (!hasNew)
            {
                return;
            }
            int errNo = 0;
            foreach (DataRow dr in targetTable.Rows)
            {
                string estateID = dr["RealEstateID"].ToString();

                //根据楼盘和域名得到一条楼盘的论坛数据
                try
                {
                    string cityname = dr["City"].ToString();
                    if (cityDomain.ContainsKey(cityname))
                    {
                        string url = string.Format(urlFormat, cityDomain[cityname], dr["RealEstateID"].ToString());
                        DataTable tmpdt = Net.GetDTFromUrl(url);
                        if (tmpdt == null)
                        {
                            //Logger.InfoLog.InfoFormat("业主论坛接口出错，newcode={0}", estateID);
                            errNo++;
                            continue;
                        }
                        
                        if (tmpdt.Columns.Count < 6)
                        {
                            //Logger.InfoLog.InfoFormat("没有该楼盘的业主论坛数据，newcode={0},error={1}", estateID, tmpdr[1].ToString());
                            errNo++;
                            continue;
                        }
                        //if(tmpdr.ItemArray[0].ToString()==""
                        DataRow tmpdr = tmpdt.Rows[0];
                        dr["bbsTotalHits"] = tmpdr["AllUserViewCount"].ToString();
                        dr["bbsTotalClicks"] = tmpdr["AllHits"].ToString();
                        dr["bbsTotalTopics"] = tmpdr["allcount"].ToString();
                        dr["bbsCertifiedOwners"] = tmpdr["IsRealCount"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Logger.InfoLog.WarnFormat("业主论坛ProcessData()出错，newcode={0},error={1}", estateID, ex.Message);
                }
            }
            try
            {
                targetTable.Columns.Remove("City");
            }
            catch
            {
                Logger.InfoLog.Info("ReadDtEstateManage()出错");
            }
            
            //Logger.InfoLog.InfoFormat("更新业主论坛数据，出错个数:{0},成功:{1}", errNo, targetTable.Rows.Count - errNo);
        }

        protected override void WriteData()
        {
            if (!hasNew)
            {
                return;
            }
            DAL.TVPUpdate(targetTable, "EstateManageUpdateBBS", "UdtEstateManageUpdateBBS");
        }

        protected override void InitLoopCondition()
        {
            if (!hasNew)
            {
                return;
            }
            InitCityDic();
            if (cityDomain.Count == 0)
            {
                Logger.InfoLog.Warn("读取bbsCityDomain表时出错");
                hasNew = false;
            }
        }

        protected override void UpdateLoopCondition()
        {
            if (DateTime.Now.Hour >= 9 && DateTime.Now.Hour < 17)
            {
                hasNew = false;
            }
            if (!hasNew)
            {
                return;
            }
            currentMaxID = Convert.ToInt32(targetTable.Rows[targetTable.Rows.Count - 1]["id"]);
            targetTable = null;
            Console.WriteLine(currentMaxID);
        }

        protected override bool CanContinue()
        {
            return hasNew;
        }
    }
}
